import { message } from "@/utils/message";
import { addDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
import type {
  UserClassifyFormItemProps,
  UserClassifyTableProps
} from "./type/userClassifyTypes";
import { h, computed, onMounted, reactive, ref, type Ref } from "vue";
import { http } from "@/utils/http";
import { changeHttpLink } from "@/utils/test";
import { useUserStoreHook } from "@/store/modules/user";
import { useDataSyncStore } from "@/store/modules/dataSync";
import userClassifyForm from "../componentsForm/userClassifyForm.vue";

export function useUserClassifyTable(
  tableRef: Ref,
  props: UserClassifyTableProps
) {
  const form = reactive({
    tenantId: props.lesseeId || "",
    dealerId: props.dealerId || "",
    status: "",
    SearchTerm: "",
    OrderBy: ""
  });

  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const selectedNum = ref(0);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const tenantOptions = ref([]); // 租户下拉列表数据

  // 顶部统计数据
  const totalClassifyCount = ref(0);
  const activeClassifyCount = ref(0);
  const classifyUserCount = ref(0);

  const columns = [
    {
      label: "分类名称",
      prop: "Name",
      minWidth: 130
    },
    {
      label: "用户数量",
      prop: "UserCount",
      minWidth: 90
    },
    {
      label: "租户名称",
      prop: "TenantName",
      minWidth: 130
    },
    {
      label: "经销商名称",
      prop: "DealerName",
      minWidth: 130
    },
    {
      label: "创建时间",
      prop: "CreateTime",
      minWidth: 180,
      formatter: (row: any) => {
        if (!row.CreateTime) return "";
        return row.CreateTime.replace("T", "/").replace(/\.\d{3}Z?$/, "");
      }
    },
    {
      label: "操作",
      fixed: "right",
      width: 150,
      slot: "operation"
    }
  ];

  const buttonClass = computed(() => {
    return [
      "h-[20px]!",
      "reset-margin",
      "text-gray-500!",
      "dark:text-white!",
      "dark:hover:text-primary!"
    ];
  });

  // 获取、搜索列表
  function onSearch() {
    loading.value = true;
    const params = {
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      tenantId: form.tenantId || props.lesseeId || 0,
      dealerId: (props.dealerId || useUserStoreHook()?.userId) ?? 0
    };

    http
      .get(changeHttpLink("/api/UserCategorize"), { params })
      .then((res: any) => {
        console.log("获取用户分类列表:", res);
        loading.value = false;
        if (res.Success) {
          dataList.value = res.Data.Items;
          pagination.total = res.Data.TotalCount;
          // 更新顶部统计数据
          totalClassifyCount.value = res.Data.TotalCount || 0;
          activeClassifyCount.value = res.Data.TotalCount || 0;
          classifyUserCount.value = res.Data.TotalCount || 0;
        } else {
          message(res.Message, { type: "error" });
        }
      })
      .catch(err => {
        loading.value = false;
        message(err.message, { type: "error" });
      });
  }

  // 新增用户分类、修改
  function openDialog(title: string, row?: any) {
    const id = row?.Id ?? 0;
    addDialog({
      title: `${title}用户分类`,
      props: {
        formInline: {
          Id: row?.Id ?? 0,
          Name: row?.Name ?? "",
          TenantId: props.lesseeId ?? 0,
          tenantOptions: tenantOptions.value
        }
      },
      width: "640px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () =>
        h(userClassifyForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as UserClassifyFormItemProps;

        function chores() {
          message(`您${title}了分类名称为【${curData.Name}】的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据

          // 通知全局分类数据更新
          const dataSyncStore = useDataSyncStore();
          dataSyncStore.notifyCategorizeDataUpdated();
        }

        FormRef.validate(valid => {
          if (valid) {
            loading.value = true;
            const formData = {
              id: row?.Id ?? 0,
              name: curData?.Name ?? "",
              tenantId: props.lesseeId ?? 0,
              dealerId: (props.dealerId || useUserStoreHook()?.userId) ?? 0
            };

            console.log("已上传", formData);

            if (title === "创建") {
              http
                .post(changeHttpLink("/api/UserCategorize"), {
                  data: formData
                })
                .then((res: any) => {
                  if (res.Success) {
                    chores();
                  } else {
                    message(res.Message, { type: "error" });
                  }
                  loading.value = false;
                })
                .catch(err => {
                  loading.value = false;
                  message(err.message, { type: "error" });
                });
            } else {
              formData.id = id;
              http
                .request("put", changeHttpLink(`/api/UserCategorize/${id}`), {
                  data: formData
                })
                .then((res: any) => {
                  console.log("res", res);
                  if (res.Success) {
                    chores();
                  } else {
                    message(res.Message, { type: "error" });
                  }
                  loading.value = false;
                })
                .catch(err => {
                  message(err.message, { type: "error" });
                  loading.value = false;
                });
            }
          }
        });
      }
    });
  }

  // 删除
  function handleDelete(row: any) {
    http
      .request("delete", changeHttpLink(`/api/UserCategorize/${row.Id}`), {
        data: row.Id
      })
      .then((res: any) => {
        console.log(res);
        if (res.Success) {
          message(`您删除了分类名称为${row.Name}的这条数据`, {
            type: "success"
          });
          onSearch();

          // 通知全局分类数据更新
          const dataSyncStore = useDataSyncStore();
          dataSyncStore.notifyCategorizeDataUpdated();
        } else {
          message(res.Message, { type: "error" });
        }
        loading.value = false;
      })
      .catch(err => {
        loading.value = false;
        message(err.message, { type: "error" });
        console.error(err);
      });
  }

  // 批量删除 没有接口
  function onbatchDel() {
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    const listIds = curSelected.map(item => {
      return item.id;
    });
    console.log(listIds);
  }

  // 分页变化
  function handleSizeChange(val: number) {
    pagination.currentPage = 1;
    pagination.pageSize = val;
    dataList.value = [];
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val: any) {
    selectedNum.value = val.length;
    tableRef.value.setAdaptive();
  }

  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    tableRef.value.getTableRef().clearSelection();
  }

  // 重置表单
  function resetForm(formEl: any) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  // 获取租户下拉列表
  const getSelectTenant = () => {
    http
      .get(changeHttpLink("/api/Tenant/select"))
      .then((res: any) => {
        if (res.Success) {
          tenantOptions.value = res.Data;
        } else {
          message(res.Message, { type: "error" });
        }
      })
      .catch(err => {
        message(err.message, { type: "error" });
      });
  };
  // 设备检测
  function deviceDetection() {
    return window.innerWidth <= 1024;
  }
  onMounted(() => {
    getSelectTenant();
    onSearch();
  });

  return {
    form,
    formRef,
    loading,
    columns,
    dataList,
    selectedNum,
    pagination,
    buttonClass,
    tenantOptions,
    onSearch,
    resetForm,
    onbatchDel,
    openDialog,
    handleDelete,
    handleSizeChange,
    onSelectionCancel,
    handleCurrentChange,
    handleSelectionChange,
    totalClassifyCount,
    activeClassifyCount,
    classifyUserCount,
    deviceDetection
  };
}
